#!/usr/bin/env python
# -*- coding: utf-8 -*-
# 通过fofa.so第三方网站获取相同ICO网站
import re
import requests
import base64
import json
import sys
import mmh3

class Fofa(object):      #定义一个类
    def __init__(self,domain):     #初始化
        self.query = domain
        self.page = 1
        self.email = '2014802836@qq.com'
        self.api_key = '76f651df8bcc1d38899c2c530133e0f6'
        self.result = []    # 定义一个列表，接受返回结果


    def run(self):
        #获取ico的hash值
     
        url = self.query + "/favicon.ico" if '://' in self.query else 'http://' + self.query + "/favicon.ico"
        #print(url)

        try:
            r = requests.get(url, verify=False, timeout=20)
            #if r.headers['Content-Type'] == "image/x-icon":
            if sys.version_info > (3, 0):
                favicon = base64.encodebytes(r.content)
            else:
                favicon = r.content.encode('base64')

            hash1 = mmh3.hash(favicon)
            
        except Exception as e:
            print(e)
            print("[x] Network is error")
            hash1 = None

        
        print("[*]正在通过fofa查询相同ICO网站[*]")
        query = base64.b64encode(("icon_hash="+str(hash1)).encode('utf-8')).decode('utf-8')
        res = []
        
        for p in range(1, self.page + 1):   #遍历获取相同ICO地址

            url = "https://fofa.so/api/v1/search/all?email={0}&key={1}&qbase64={2}&page={3}".format(self.email,
                                                                                                        self.api_key,
                                                                                                        query, p)
            #print(url)
            r = requests.get(url = url) 
            result_json = json.loads(r.text)

            if result_json.get('results') != None:
                for item in result_json.get('results'):
                    url = item[0] if '://' in item[0] else 'http://' + item[0]
                    self.result.append(url)
                print("相同ICO网站查询完成！")
                return list(set(self.result))           
            else:
                break
